﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GraphicSplit101
{
    /// <summary>
    /// 自对比算法检测
    /// </summary>
    public partial class UCInspectionForSelfCompare : UserControl
    {

        private Bitmap originalBitmap = GraphicSplit101.Properties.Resources.Sample2_3;  //原图

        public Bitmap OriginalBitmap
        {
            get { return originalBitmap; }
            set { originalBitmap = value; }
        }

        private Bitmap processedBitmap = GraphicSplit101.Properties.Resources.Sample2_3; //处理过的图

        public Bitmap ProcessedBitmap
        {
            get { return processedBitmap; }
            set { processedBitmap = value; }
        }

        /// <summary>
        /// 样本方差数据
        /// </summary>
        private List<InspectionEigenvalueDetail> sampleInspectionEigenvalueDetailList;

        private int splitCount = 6; //默认切割次数设为6

        //public int SplitCount
        //{
        //    get { return splitCount; }
        //    set { splitCount = value; }
        //}

        private int pid = 1;

        public int Pid
        {
            get { return pid; }
            set { pid = value; }
        }

        private bool isOK = true;

        public bool IsOK
        {
            get { return isOK; }
            set { isOK = value; }
        }

        private int badLayer = -1;

        /// <summary>
        /// 出错的层，从1开始
        /// </summary>
        public int BadLayer 
        {
            get { return badLayer; }
            set { badLayer = value; }
        }

        private string user = "admin";

        public string User
        {
            get { return user; }
            set { user = value; }
        }


        public UCInspectionForSelfCompare()
        {
            InitializeComponent();
            pictureBox.Image = originalBitmap;
        }

        private void btnInspection_Click(object sender, EventArgs e)
        {
            try
            {
                btnInspection.Enabled = false;
                isOK = true;
                //先从数据库读入样本方差数据
                if (sampleInspectionEigenvalueDetailList == null)
                {
                    ReadSampleInspectionEigenvalueDetailList();
                }

                //检测区域
                DataTable dt = DBUtils.GetDataTable("select top 1 [top],[left],width,height from InspectionAreaDetail where [type]=2 and pid='" + Pid + "'");
                //忽略区域
                DataTable dtInspectionIgnore = DBUtils.GetDataTable("select [top],[left],width,height from InspectionAreaDetail where [type]=3 and pid='" + Pid + "'");
                byte[,] grayBytes = GetGrayBytes2D(processedBitmap);
                IgnoreBytes(grayBytes, dtInspectionIgnore);
                byte[,] availableBytes;
                if (dt.Rows.Count > 0)
                {
                    DataRow dataRow = dt.Rows[0];
                    Rectangle rectangle = new Rectangle(Convert.ToInt32(dataRow["left"]), Convert.ToInt32(dataRow["top"]),
                        Convert.ToInt32(dataRow["width"]), Convert.ToInt32(dataRow["height"]));
                    availableBytes = GetAvailableBytes2D(grayBytes, rectangle);
                }
                else
                {
                    availableBytes = grayBytes;
                }
                ucGraphicSplit1.AvailableBytes = availableBytes;
                ucGraphicSplit1.SplitCount = splitCount;
                List<List<Rectangle>> listSplitGrayBlockPostion = ucGraphicSplit1.SplitGraphicBytes();  //切割并反回每层每块的L,T,W,H
                List<List<byte[,]>> listBlockBytes = GetListBlockBytes(availableBytes, listSplitGrayBlockPostion);
                List<InspectionEigenvalueDetail> productInspectionEigenvalueDetailList = GetInspectionEigenvalueDetailList(listBlockBytes);
                StatisticsEigenValues(listBlockBytes, productInspectionEigenvalueDetailList);
                Inspection(productInspectionEigenvalueDetailList);
                MessageBox.Show("成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show("发生错误：" + ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {
                btnInspection.Enabled = true;
            }
        }

        /// <summary>
        /// 检测
        /// </summary>
        /// <param name="productInspectionEigenvalueDetailList"></param>
        private void Inspection(List<InspectionEigenvalueDetail> productInspectionEigenvalueDetailList)
        {
            StringBuilder sb = new StringBuilder();
            List<Rectangle> badRectangleList = new List<Rectangle>();
            int maxBadLayer = -1;   //出错的最大层号，从0开始。只记录最大层中出错的区域
            double[] inspectionPreAreaDetails = GetInspectionPreAreaDetails();
            for (int i = splitCount - 1; i >= 0; i--)
            {
                for (int j = 0; j < Convert.ToInt32(Math.Pow(2, i + 1)); j++)
                {
                    InspectionEigenvalueDetail productInspectionEigenvalueDetail = (from item in productInspectionEigenvalueDetailList
                                                                                    where item.Layer == i && item.Piece == j
                                                                                    select item).First();

                    InspectionEigenvalueDetail sampleInspectionEigenvalueDetail = (from item in sampleInspectionEigenvalueDetailList
                                                                                    where item.Layer == i && item.Piece == j
                                                                                    select item).First();

                    double productVariance = productInspectionEigenvalueDetail.Variance;
                    double sampleVariance = sampleInspectionEigenvalueDetail.Variance;

                    double inspectionPreAreaDetail = GetInspectionPreAreaDetail(inspectionPreAreaDetails, i, j);

                    int flag = 0;   //表示每次比较的结果，0为好，1为坏

                    //方差比较
                    if (productVariance * inspectionPreAreaDetail > sampleVariance)
                    {
                        isOK = false;
                        flag = 1;
                        BadLayer = i + 1;
                        if (i > maxBadLayer)
                        {
                            maxBadLayer = i;
                        }
                        if (maxBadLayer == i)
                        {
                            string[] ltwh = sampleInspectionEigenvalueDetail.Area.Split(',');
                            badRectangleList.Add(new Rectangle(Convert.ToInt32(ltwh[0]), Convert.ToInt32(ltwh[1]), Convert.ToInt32(ltwh[2]), Convert.ToInt32(ltwh[3])));
                        }
                    }
                    //直方图比较
                    else
                    {
                        //预设区域容差若是0，则忽略检测
                        if (inspectionPreAreaDetail > 0)
                        {
                            int[] productEigenValues = productInspectionEigenvalueDetail.EigenValues;
                            int[] sampleEigenValues = sampleInspectionEigenvalueDetail.EigenValues;
                            for (int n = 0; n < productEigenValues.Length; n++)
                            {
                                if (productEigenValues[n] > sampleEigenValues[n] * 1.1
                                    || productEigenValues[n] < sampleEigenValues[n] * 0.9)
                                {
                                    isOK = false;
                                    flag = 1;
                                    BadLayer = i + 1;
                                    if (i > maxBadLayer)
                                    {
                                        maxBadLayer = i;
                                    }
                                    if (maxBadLayer == i)
                                    {
                                        string[] ltwh = sampleInspectionEigenvalueDetail.Area.Split(',');
                                        badRectangleList.Add(new Rectangle(Convert.ToInt32(ltwh[0]), Convert.ToInt32(ltwh[1]), Convert.ToInt32(ltwh[2]), Convert.ToInt32(ltwh[3])));
                                    }
                                }
                            }
                        }
                    }
                    if (flag == 1)
                    {
                        sb.Append("insert into InspectionNoteDetail([PID], [Layer], [Eigenvalue], [CurrentValue], [Area], [Flag]) ");
                        sb.Append(" values(" + Pid + ", " + (i + 1) + ", '" + sampleInspectionEigenvalueDetail.Variance + "', '" + productInspectionEigenvalueDetail.Variance + "','" + sampleInspectionEigenvalueDetail.Area + "', " + flag + ")\n");
                        //sb.Append("insert into InspectionNoteDetail([PID], [Layer], [Eigenvalue], [CurrentValue], [Area], [Flag],MessageEx1,MessageEx2) ");
                        //sb.Append(" values(" + Pid + ", " + (i + 1) + ", '" + sampleInspectionEigenvalueDetail.Variance + "', '" + productInspectionEigenvalueDetail.Variance + "','" + sampleInspectionEigenvalueDetail.Area + "', " + flag + ", '" + productInspectionEigenvalueDetail.GetEigenValuesWithComma() + " ','" + sampleInspectionEigenvalueDetail.GetEigenValuesWithComma() + "')\n");
                    }
                }
            }
            sb.Append("insert into InspectionNote([ProductID], [User], [OPTIME], [Result]) ");
            sb.Append(" values(" + Pid + ", '" + User + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "', " + (isOK ? 0 : 1) + ")\n");
            DBUtils.ExecuteSql(sb.ToString());
            pictureBox.Refresh();
            foreach (Rectangle rectangle in badRectangleList)
            {
                DrawArea(rectangle, pictureBox);
            }
        }

        private void DrawArea(Rectangle rectangle, PictureBox pictureBox)
        {
            if (rectangle != null)
            {
                Graphics g = pictureBox.CreateGraphics();
                Pen pen = new Pen(Color.Red, 2f);
                float XRadio = (float)pictureBox.Width / pictureBox.Image.Width;
                float YRadio = (float)pictureBox.Height / pictureBox.Image.Height;

                Rectangle rectangleTmp = new Rectangle(Convert.ToInt32(rectangle.X * XRadio), Convert.ToInt32(rectangle.Y * YRadio), Convert.ToInt32(rectangle.Width * XRadio), Convert.ToInt32(rectangle.Height * YRadio));
                g.DrawRectangle(pen, rectangleTmp);
                g.Dispose();
            }
        }

        /// <summary>
        /// 根据layer和piece得到那一块的容差
        /// </summary>
        /// <param name="inspectionPreAreaDetails"></param>
        /// <param name="layer">从0开始</param>
        /// <param name="piece">从0开始</param>
        /// <returns></returns>
        private double GetInspectionPreAreaDetail(double[] inspectionPreAreaDetails, int layer, int piece)
        {
            //下面的公式改动了一下，减1，下标从0开始
            if (layer < 5)
            {
                if (layer % 2 == 0)
                {
                    //t4[x]=(t5[2x]+t5[2x+1])/2
                    return (GetInspectionPreAreaDetail(inspectionPreAreaDetails, layer + 1, 2 * piece) + GetInspectionPreAreaDetail(inspectionPreAreaDetails, layer + 1, 2 * piece)) / 2;
                }
                else
                {
                    //t3[x]=(t4[x]+t4[x+n])/2
                    //n = layer + 1
                    return (GetInspectionPreAreaDetail(inspectionPreAreaDetails, layer + 1, piece) + GetInspectionPreAreaDetail(inspectionPreAreaDetails, layer + 1, piece + layer + 1)) / 2;
                }
            }
            else if (layer > 5)
            {
                if (layer % 2 == 0)
                {
                    //t6[x]=t5[x-n*y/2] 偶数行
                    //t6[x]=t5[x-n*(y/2+1)] 奇数行
                    int n = Convert.ToInt32(Math.Pow(2, layer / 2)); //每行块数
                    int y = piece / n;  //行号，从0开始
                    if (y % 2 == 0)
                    {
                        return GetInspectionPreAreaDetail(inspectionPreAreaDetails, layer - 1, piece - n * y / 2);
                    }
                    else
                    {
                        return GetInspectionPreAreaDetail(inspectionPreAreaDetails, layer - 1, piece - n * (y / 2 + 1));
                    }
                }
                else
                {
                    //t7[x]=t6[x/2] 偶数列
                    //t7[x]=t6[(x-1)/2] 奇数列
                    if (piece % 2 == 0)
                    {
                        return GetInspectionPreAreaDetail(inspectionPreAreaDetails, layer - 1, piece / 2);
                    }
                    else
                    {
                        return GetInspectionPreAreaDetail(inspectionPreAreaDetails, layer - 1, (piece - 1) / 2);
                    }
                }
            }
            else
            {
                return inspectionPreAreaDetails[piece];
            }
        }

        /// <summary>
        /// 得到容差
        /// </summary>
        /// <returns></returns>
        private double[] GetInspectionPreAreaDetails()
        {
            double[] inspectionPreAreaDetails = new double[64];
            DataTable dt = DBUtils.GetDataTable("select top 8 * from InspectionPreAreaDetail where PID=" + Pid + " order by id");
            for (int i = 0, n = 0; i < 8; i++)
            {
                DataRow dr = dt.Rows[i];
                for (int j = 0; j < 8; j++, n++)
                {
                    inspectionPreAreaDetails[n] = Convert.ToDouble(dr["CO" + (j + 1)]);
                }
            }
            return inspectionPreAreaDetails;                        
        }

        /// <summary>
        /// 分段统计每层每块的灰度值个数
        /// </summary>
        /// <param name="listBlockBytes"></param>
        private void StatisticsEigenValues(List<List<byte[,]>> listBlockBytes, List<InspectionEigenvalueDetail> inspectionEigenvalueDetailList)
        {
            int size = 32;
            int blockSize = 8;
            for (int i = 0; i < listBlockBytes.Count; i++)
            {
                List<byte[,]> blockBytes = listBlockBytes[i];
                for (int j = 0; j < blockBytes.Count; j++)
                {
                    byte[,] bytes = blockBytes[j];
                    int[] eigenValues = new int[size];
                    foreach (byte b in bytes)
                    {
                        eigenValues[b / blockSize]++;
                    }
                    var inspectionEigenvalueDetail = (from item in inspectionEigenvalueDetailList
                                                      where item.Layer == i && item.Piece == j
                                                      select item).First();
                    inspectionEigenvalueDetail.EigenValues = eigenValues;
                }
            }

        }

        /// <summary>
        /// 从数据库读入样本数据
        /// </summary>
        private void ReadSampleInspectionEigenvalueDetailList()
        {
            sampleInspectionEigenvalueDetailList = new List<InspectionEigenvalueDetail>();
            DataTable dt = DBUtils.GetDataTable("select [Layer],[Piece],[Area],[Variance],[EigenValue] FROM [InspectionEigenvalueDetail] where pid=" + Pid);
            foreach (DataRow row in dt.Rows)
            {
                InspectionEigenvalueDetail detail = new InspectionEigenvalueDetail(Convert.ToInt32(row["Layer"]), Convert.ToInt32(row["Piece"]),
                    row["Area"].ToString(), Convert.ToDouble(row["Variance"]));
                string eigenValueStr = row["EigenValue"].ToString();
                if (!string.IsNullOrEmpty(eigenValueStr))
                {
                    detail.SetEigenValuesWithComma(eigenValueStr);
                }
                sampleInspectionEigenvalueDetailList.Add(detail);
            }
        }

        /// <summary>
        /// 将忽略区域的点设为0
        /// </summary>
        /// <param name="grayBytes"></param>
        /// <param name="dtInspectionIgnore"></param>
        private void IgnoreBytes(byte[,] grayBytes, DataTable dtInspectionIgnore)
        {
            foreach (DataRow dr in dtInspectionIgnore.Rows)
            {
                Rectangle rectangle = new Rectangle(Convert.ToInt32(dr["left"]), Convert.ToInt32(dr["top"]),
                        Convert.ToInt32(dr["width"]), Convert.ToInt32(dr["height"]));
                for (int i = rectangle.Left; i < rectangle.Left + rectangle.Width; i++)
                {
                    for (int j = rectangle.Top; j < rectangle.Top + rectangle.Height; j++)
                    {
                        grayBytes[i, j] = 0;
                    }
                }
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        private void SaveListBlockBytes(List<InspectionEigenvalueDetail> inspectionEigenvalueDetailList)
        {
            string sql = BuildInsertSql(inspectionEigenvalueDetailList);
            DBUtils.ExecuteSql(sql);
        }

        /// <summary>
        /// 构建插入SQL
        /// </summary>
        /// <param name="inspectionEigenvalueDetailList"></param>
        /// <returns></returns>
        private string BuildInsertSql(List<InspectionEigenvalueDetail> inspectionEigenvalueDetailList)
        {
            StringBuilder sb = new StringBuilder();
            //先把数据库里的数据清空再插入
            sb.Append("delete from InspectionEigenvalueDetail where PID=" + Pid + "\n");
            foreach (InspectionEigenvalueDetail inspectionEigenvalueDetail in inspectionEigenvalueDetailList)
            {
                sb.Append("insert into InspectionEigenvalueDetail(PID, Layer, Piece, Area, Variance, EigenValue)");

                sb.Append(" values(" + Pid + ", " + inspectionEigenvalueDetail.Layer + ", " + inspectionEigenvalueDetail.Piece
                    + ", '" + inspectionEigenvalueDetail.Area + "', " + inspectionEigenvalueDetail.Variance
                    + ", '" + inspectionEigenvalueDetail.GetEigenValuesWithComma() + "')\n");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 得到每一层每一块的方差list
        /// </summary>
        /// <param name="listBlockBytes"></param>
        /// <returns></returns>
        private List<InspectionEigenvalueDetail> GetInspectionEigenvalueDetailList(List<List<byte[,]>> listBlockBytes)
        {
            List<InspectionEigenvalueDetail> inspectionEigenvalueDetailList = new List<InspectionEigenvalueDetail>();
            for (int i = 0; i < listBlockBytes.Count; i++)
            {
                List<byte[,]> blockBytes = listBlockBytes[i];
                for (int j = 0; j < blockBytes.Count; j++)
                {
                    byte[,] bytes = blockBytes[j];
                    inspectionEigenvalueDetailList.Add(new InspectionEigenvalueDetail(i, j, "", GetVariance(bytes)));
                }
            }
            return inspectionEigenvalueDetailList;
        }

        /// <summary>
        /// 计算方差
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        private double GetVariance(byte[,] bytes)
        {
            double variance = 0;
            double pixelCountX = 1;
            double pixelCountY = 1;
            double pixelCount = 1;
            double grayAverage = 0;
            double graySum = 0;
            try
            {
                pixelCountX = bytes.GetLength(0);
                pixelCountY = bytes.GetLength(1);
                pixelCount = (pixelCountX * pixelCountY);
                for (int j = 0; j < pixelCountY; j++)
                {
                    for (int i = 0; i < pixelCountX; i++)
                    {
                        int gray = bytes[i, j];
                        graySum += gray;
                    }
                }
                grayAverage = graySum / pixelCount;
                double diffValueSum = 0;
                for (int j = 0; j < pixelCountY; j++)
                {
                    for (int i = 0; i < pixelCountX; i++)
                    {
                        diffValueSum += Math.Pow(bytes[i, j] - grayAverage, 2);
                    }
                }
                variance = diffValueSum / pixelCount;
                variance = (int)Math.Pow(variance, 0.5);
                return variance;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return Double.MaxValue;
            }
        }

        /// <summary>
        /// 得到每块的bytes
        /// </summary>
        /// <param name="availableBytes"></param>
        /// <param name="listSplitGrayBlockPostion"></param>
        /// <returns></returns>
        private static List<List<byte[,]>> GetListBlockBytes(byte[,] availableBytes, List<List<Rectangle>> listSplitGrayBlockPostion)
        {
            List<List<byte[,]>> listBlockBytes = new List<List<byte[,]>>();
            foreach (List<Rectangle> rectangles in listSplitGrayBlockPostion)
            {                
                List<byte[,]> listBytes = new List<byte[,]>();
                foreach (Rectangle rectangle in rectangles)
                {
                    byte[,] bytes = new byte[rectangle.Width, rectangle.Height];
                    for (int k = rectangle.Top, n = 0; k < rectangle.Top + rectangle.Height; k++, n++)
                    {
                        for (int i = rectangle.Left, j = 0; i < rectangle.Left + rectangle.Width; i++, j++)
                        {
                            bytes[j, n] = availableBytes[i, k];
                        }
                    }
                    listBytes.Add(bytes);
                }
                listBlockBytes.Add(listBytes);
            }
            return listBlockBytes;
        }

        /// <summary>
        /// 得到有效区域2D bytes
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        private static byte[,] GetAvailableBytes2D(byte[,] grayBytes, Rectangle rectangle)
        {
            byte[,] availableBytes = new byte[rectangle.Width, rectangle.Height];
            for (int k = rectangle.Top, n = 0; k < rectangle.Top + rectangle.Height; k++, n++)
            {
                for (int i = rectangle.Left, j = 0; i < rectangle.Left + rectangle.Width; i++, j++)
                {
                    availableBytes[j, n] = grayBytes[i, k];
                }
            }
            return availableBytes;
        }

        /// <summary>
        /// GetGrayBytes2D:下标0代表x轴坐标，1代表y轴坐标。默认提取绿色通道像素值。
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        private static byte[,] GetGrayBytes2D(Bitmap bitmap)
        {
            if (bitmap == null) return null;
            string strPixelFormat = bitmap.PixelFormat.ToString();
            if (strPixelFormat == "Format8bppIndexed")
            {
                return ConvertGrayBytesToDoubleArray(GetGrayBytesFor8bit(bitmap), bitmap.Width, bitmap.Height);
            }
            else
            {
                return ConvertGrayBytesToDoubleArray(GetGrayBytesFor32bit(bitmap, 2), bitmap.Width, bitmap.Height);
            }
        }
        private static byte[,] ConvertGrayBytesToDoubleArray(byte[] grayBytes, int imageWidth, int imageHeight)
        {
            byte[,] processedGrayBytes = new byte[imageWidth, imageHeight];
            int k = 0;
            for (int j = 0; j < imageHeight; j++)
            {
                for (int i = 0; i < imageWidth; i++)
                {
                    processedGrayBytes[i, j] = grayBytes[k++];
                }
            }
            return processedGrayBytes;
        }
        private static byte[] GetGrayBytesFor8bit(Bitmap bitmap)
        {
            byte[] grayValues = null;
            try
            {
                if (bitmap != null)
                {
                    Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                    System.Drawing.Imaging.BitmapData bmpData = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);
                    IntPtr ptr = bmpData.Scan0;
                    int bytes = bitmap.Width * bitmap.Height;
                    grayValues = new byte[bytes];
                    System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, 0, bytes);
                    bitmap.UnlockBits(bmpData);
                }
                return grayValues;
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("GetGrayBytesFor8bit:{0}", ex.Message));
                return null;
            }
        }
        private static byte[] GetGrayBytesFor32bit(Bitmap bitmap, int intMethod)
        {
            byte[] rgbValues = null;
            byte[] grayValues = null;
            if (bitmap != null)
            {
                double r = 0, g = 0, b = 0;
                switch (intMethod)
                {
                    case 0:
                        {
                            r = 0.299;
                            g = 0.587;
                            b = 0.114;
                            break;
                        }
                    case 1:
                        {
                            r = 1;
                            g = 0;
                            b = 0;
                            break;
                        }
                    case 2:
                        {
                            r = 0;
                            g = 1;
                            b = 0;
                            break;
                        }
                    case 3:
                        {
                            r = 0;
                            g = 0;
                            b = 1;
                            break;
                        }
                    default:
                        r = 0;
                        g = 1;
                        b = 0;
                        break;
                }
                try
                {
                    Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                    System.Drawing.Imaging.BitmapData bmpData = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);
                    IntPtr ptr = bmpData.Scan0;
                    int bytes = bitmap.Width * bitmap.Height;
                    int rgbBytes = bytes * 3;
                    rgbValues = new byte[rgbBytes];
                    grayValues = new byte[bytes];
                    System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, rgbBytes);
                    int j = 0;
                    for (int i = 0; i < rgbBytes; i += 3)
                    {
                        double colorTemp = rgbValues[i + 2] * r + rgbValues[i + 1] * g + rgbValues[i] * b;
                        grayValues[j++] = (byte)colorTemp;
                    }
                    bitmap.UnlockBits(bmpData);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("GetGrayBytesFor32bit:{0}", ex.Message));
                }
            }
            return grayValues;
        }
    }
}
